#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+10;
int V[N],W[N];
const int C = 500 + 10;
const int CLMT = 500;
int ql[N],qr[N],qc[N];
long long ans[N];
struct segment_tree{
    vector<int> qs[N<<2];
    void build(int now,int l,int r){
        if(l == r){
            for(int v:qs[now]){
                if(qc[v] >= W[l]){
                    ans[v] = V[l];
                }
            }
            return;
        }
        int mid = (l + r)/2;
        vector<vector<long long>> L,R;
        vector<long long> dp(CLMT + 1,0);
        for(int i = mid + 1;i <= r;i++){
            for(int j = CLMT;j >= W[i];j--){
                dp[j] = max(dp[j],dp[j - W[i]] + V[i]);
            }
            for(int j = 1;j <= CLMT;j++){
                dp[j] = max(dp[j],dp[j - 1]);
            }
            R.push_back(dp);
        }
        dp = vector<long long>(CLMT + 1,0);
        for(int i = mid;i >= l;i--){
            for(int j = CLMT;j >= W[i];j--){
                dp[j] = max(dp[j],dp[j - W[i]] + V[i]);
            }
            for(int j = 1;j <= CLMT;j++){
                dp[j] = max(dp[j],dp[j - 1]);
            }
            L.push_back(dp);
        }
        for(int v:  qs[now]){
            long long as = 0;
            for(int j = 0;j <= qc[v];j++){
                as = max(as,L[mid - ql[v]][j] + R[qr[v] - mid - 1][qc[v] - j]);
            }
            ans[v] = as;
        }
        build(now<<1,l,mid);
        build(now<<1|1,mid+1,r);
    }
    void query(int now,int l,int r,int x,int y,int idx){
        if(l == r){
            qs[now].push_back(idx);
            return;
        }
        int mid = (l + r)/2;
        if(l <= x && y <= r && x <= mid && mid < y){
            qs[now].push_back(idx);
            return;
        }
        if(y <= mid){
            return query(now<<1,l,mid,x,y,idx);
        }else{
            return query(now<<1|1,mid+1,r,x,y,idx);
        }
    }
}sg;
int main(){
    int n;
    cin>>n;
    for(int i = 1;i<=n;i++){
        cin>>W[i]>>V[i];
    }
    int q;
    cin>>q;
    for(int i = 1;i<=q;i++){
        cin>>ql[i]>>qr[i]>>qc[i];
        sg.query(1,1,n,ql[i],qr[i],i);
    }
    sg.build(1,1,n);
    for(int i = 1;i<=q;i++){
        cout<<ans[i]<<'\n';
    }
}